﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UI.Data;

namespace UI.Controllers
{
    public class SportController : Controller
    {
        //
        // GET: /Sport/
        private readonly SPORTSALEEntities context = new SPORTSALEEntities();

        public ActionResult Index()
        {
            return View(context.Deportes);
        }

        //
        // GET: /Sport/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Sport/Create

        [HttpPost]
        public ActionResult Create(Deportes sp)
        {
            try
            {
                if (context.Deportes.Any(x => x.Nombre == sp.Nombre))
                {
                    ModelState.AddModelError("Name", "Ya existe un deporte con el mismo nombre");
                    return View();
                }

                sp.Categorias = context.Categorias.Where(x => x.Id == sp.IdCategoria).First();
                context.Deportes.AddObject(sp);                
                context.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Sport/Edit/5

        public ActionResult Edit(int id)
        {
            return View(context.Deportes.ToList().Where(x => x.Id == id).First());
        }

        //
        // POST: /Sport/Edit/5

        [HttpPost]
        public ActionResult Edit(Deportes sp)
        {
            try
            {
                Deportes old = context.Deportes.Where(x => x.Id == sp.Id).First();
                old.Nombre = sp.Nombre;
                old.IdCategoria= sp.IdCategoria;
                old.Categorias = context.Categorias.Where(x => x.Id == sp.IdCategoria).First();

                context.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Sport/Delete/5

        public ActionResult Delete(int id)
        {
            return View(context.Deportes.Where(x => x.Id == id).First());
        }

        //
        // POST: /Sport/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection col)
        {
            context.Deportes.DeleteObject(context.Deportes.Where(x => x.Id == id).First());
            context.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
